package com.zkingsoft.web.action;

import com.google.gson.Gson;
import com.matrix.core.anotations.SaveRequestToken;
import com.matrix.core.constance.MatrixConstance;
import com.matrix.core.constance.SystemErrorCode;
import com.matrix.core.constance.SystemMessageCode;
import com.matrix.core.exception.GlobleException;
import com.matrix.core.pojo.AjaxResult;
import com.matrix.core.pojo.PaginationVO;
import com.matrix.core.tools.ModelUtils;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.UUIDUtil;
import com.matrix.core.tools.WebUtil;
import com.zkingsoft.common.bean.SysUsers;
import com.zkingsoft.web.bean.Product;
import com.zkingsoft.web.bean.ProductAlbum;
import com.zkingsoft.web.bean.ProductAttrDef;
import com.zkingsoft.web.bean.ProductAttrRef;
import com.zkingsoft.web.dao.ProductAlbumDao;
import com.zkingsoft.web.dao.ProductAttrDefDao;
import com.zkingsoft.web.dao.ProductAttrRefDao;
import com.zkingsoft.web.dao.ProductDao;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @description (产品)
 * @author 姜友瑶
 * @date 2018-12-12 13:44
 */
@Controller
@RequestMapping(value = "admin/product")
public class ProductAction {

	@Autowired
	private ProductDao productDao;

	@Autowired
	private ProductAttrDefDao productAttrDefDao;
	@Autowired
	ProductAlbumDao productAlbumDao;

	@Autowired
	ProductAttrRefDao productAttrRefDao;

	// 记录编辑前的值Before_Edit_Value
	public static final String BEV = "Product_BEV";

	/**
	 * 列显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(Product product, PaginationVO pageVo) {
		if (pageVo == null) {
			pageVo = new PaginationVO();
		}
		SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
		product.setCompanyId(user.getCompanyId());
		List<Product> dataList = productDao.selectInPage(product, pageVo);
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_SUCCESS, dataList, productDao.selectTotalRecord(product));
		return result;
	}

	/**
	 * 查询产品的各种属性
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年12月14日
	 * @param product
	 * @return
	 */
	@RequestMapping(value = "/findProductAttr")
	public @ResponseBody AjaxResult findProductAttr(Product product) {
		ProductAttrRef productAttrRef = new ProductAttrRef();
		productAttrRef.setProductId(product.getId());
		productAttrRef.setIsSku(ProductAttrRef.SKU);
		List<ProductAttrRef> skus = productAttrRefDao.selectByModel(productAttrRef);

		productAttrRef.setIsSku(ProductAttrRef.NO_SKU);
		List<ProductAttrRef> attrs = productAttrRefDao.selectByModel(productAttrRef);

		ProductAlbum productAlbum = new ProductAlbum();
		productAlbum.setProductId(product.getId());
		List<ProductAlbum> albums = productAlbumDao.selectByModel(productAlbum);

		AjaxResult result = new AjaxResult();
		result.setStatus(AjaxResult.STATUS_SUCCESS);
		result.putInMap("albums", albums);
		result.putInMap("skus", skus);
		result.putInMap("attrs", attrs);
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/addProduct")
	@Transactional
	public @ResponseBody AjaxResult addProduct(Product product) {
		SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
		product.setId(UUIDUtil.getRandomID());
		product.setCreateBy(user.getSuName());
		product.setUpdateBy(user.getSuName());
		product.setCompanyId(user.getCompanyId());

		// 设置产品的属性
		updateProductAttr(product, user);

		int i = productDao.insert(product);

		if (i > 0) {
			return new AjaxResult(AjaxResult.STATUS_SUCCESS, SystemMessageCode.ADD_SUCCES, "产品");
		} else {
			throw new GlobleException(SystemErrorCode.DATA_ADD_FAIL);
		}
	}

	private void updateProductAttr(Product product, SysUsers user) {
		// 插入相册
		if(StringUtils.isNotBlank(product.getAlbumStr())){
			ProductAlbum[] array = new Gson().fromJson(product.getAlbumStr(), ProductAlbum[].class);
			for (ProductAlbum productAlbum : array) {
				productAlbum.setProductId(product.getId());
				productAlbum.setCompanyId(user.getCompanyId());
				productAlbum.setId(UUIDUtil.getRandomID());
				productAlbum.setCreateBy(user.getSuName());
				productAlbum.setUpdateBy(user.getSuName());
				if (productAlbum.getIsMain().equals(1)) {
					product.setImg(productAlbum.getImg());
				}
			}
			if (array.length > 0) {
				productAlbumDao.batchInsert(Arrays.asList(array));
			}
		}
	
		
		if(StringUtils.isNotBlank(product.getSkusStr())){
			// 插入sku属性
			ProductAttrRef[] attrArray = new Gson().fromJson(product.getSkusStr(), ProductAttrRef[].class);
			for (ProductAttrRef productAttrRef : attrArray) {

				// 对sku的id进行排序，方便组合查询
				List<String> attr = StringUtils.strToCollToString(productAttrRef.getAttrId(), ",");
				Collections.sort(attr);
				productAttrRef.setAttrId(StringUtils.collToStr(attr, ","));

				productAttrRef.setProductId(product.getId());
				productAttrRef.setId(UUIDUtil.getRandomID());
				productAttrRef.setCreateBy(user.getSuName());
				productAttrRef.setUpdateBy(user.getSuName());
				productAttrRef.setIsSku(ProductAttrRef.SKU);
				productAttrRef.setCompanyId(user.getCompanyId());
			}
			if (attrArray.length > 0) {
				productAttrRefDao.batchInsert(Arrays.asList(attrArray));
			}
		}
		

		// 解析普通属性
		if (StringUtils.isNotBlank(product.getAttrs())) {
			List<String> attrs = StringUtils.strToColl(product.getAttrs(), ",");
			List<ProductAttrRef> productAttrRefList = new ArrayList<>();
			for (String string : attrs) {
				ProductAttrRef productAttrRef = new ProductAttrRef();
				productAttrRef.setAttrId(string);
				productAttrRef.setProductId(product.getId());
				productAttrRef.setId(UUIDUtil.getRandomID());
				productAttrRef.setCreateBy(user.getSuName());
				productAttrRef.setUpdateBy(user.getSuName());
				productAttrRef.setCompanyId(user.getCompanyId());
				productAttrRef.setIsSku(ProductAttrRef.NO_SKU);
				productAttrRefList.add(productAttrRef);
			}
			if (CollectionUtils.isNotEmpty(productAttrRefList)) {
				productAttrRefDao.batchInsert(productAttrRefList);
			}
		}
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modifyProduct")
	@Transactional
	public @ResponseBody AjaxResult modifyProduct(Product newProduct) {
		SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
		Product oldProduct = WebUtil.getSessionAttribute(BEV);
		// 删除现有的属性
		ProductAttrRef productAttrRef = new ProductAttrRef();
		productAttrRef.setProductId(oldProduct.getId());
		productAttrRefDao.deleteByModel(productAttrRef);

		// 删除现有的相册
		ProductAlbum productAlbum = new ProductAlbum();
		productAlbum.setProductId(oldProduct.getId());
		productAlbumDao.deleteByModel(productAlbum);

		// 设置产品的属性
		updateProductAttr(newProduct, user);

		int i = 0;
		Map<String, Object> modifyMap = null;
		try {
			if (!ModelUtils.isModified(oldProduct, newProduct)) {
				i = MatrixConstance.DML_SUCCESSS;
			}
			modifyMap = ModelUtils.comparePojo2Map(oldProduct, newProduct);
		} catch (Exception e) {
			throw new GlobleException(SystemErrorCode.DATA_UPDATE_FAIL, e, newProduct);
		}
		if (modifyMap.size() > 0) {
			modifyMap.put("id", oldProduct.getId());
			productDao.updateByMap(modifyMap);
		}
		i = MatrixConstance.DML_SUCCESSS;
		WebUtil.removeSessionAttribute(BEV);

		if (i > 0) {
			return new AjaxResult(AjaxResult.STATUS_SUCCESS, SystemMessageCode.UPDATE_SUCCES, "产品");
		} else {
			throw new GlobleException(SystemErrorCode.DATA_UPDATE_FAIL);
		}
	}

	/**
	 * 进入修改界面
	 */
	@SaveRequestToken
	@RequestMapping(value = "/editForm")
	public String editForm(String id) {
		Product product;
		if (id != null) {
			product = productDao.selectById(id);
			WebUtil.getRequest().setAttribute("obj", product);
			WebUtil.setSessionAttribute(BEV, product);
		}

		// 查询一级SKU一级SKU中的下级
		SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
		ProductAttrDef productAttrDef = new ProductAttrDef();
		productAttrDef.setParentId("0");
		productAttrDef.setIsSku(ProductAttrRef.SKU);
		productAttrDef.setCompanyId(user.getCompanyId());
		List<ProductAttrDef> productAttrDefList = productAttrDefDao.selectByModel(productAttrDef);
		WebUtil.setRequestAttribute("skus", productAttrDefList);
		return "admin/web/Product-form";
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		List<String> ids = StringUtils.strToCollToString(keys, ",");
		int i = productDao.deleteByIds(ids);
		if (i > 0) {
			return new AjaxResult(AjaxResult.STATUS_SUCCESS, SystemMessageCode.DELETE_SUCCES, i);
		} else {
			throw new GlobleException(SystemErrorCode.DATA_DELETE_FAIL);
		}
	}

}